﻿using AutoMapper;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;

namespace B.Z.BasicData.API.Write.Application.Menu
{
    public class MenuUpdateCommandHandler : IRequestHandler<MenuUpdateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Menu> menuRepository;
        private readonly IMapper mapper;

        public MenuUpdateCommandHandler(IBaseRepository<T_Menu> menuRepository, IMapper mapper)
        {
            this.menuRepository = menuRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(MenuUpdateCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            result.Message = "添加成功";
            var menu = menuRepository.GetAll().FirstOrDefault(p => p.MenuName == request.MenuName&&p.Id!=request.Id);
            if (menu != null)
            {
                result.Code = APIEnum.faile;
                result.Message = "菜单名称已存在，请重新输入";
                return await Task.FromResult(result);
            }
            var model = mapper.Map<T_Menu>(request);
            model.UpdateTime = DateTime.Now;
            result.Data= await menuRepository.Update(model);
            return await Task.FromResult(result);
        }
    }
}
